package com.shoute.ai.utils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;

public class MultipartUtil {
    private static final String BOUNDARY = "===" + System.currentTimeMillis() + "===";

    public static String sendMultipartRequest(String urlString, String prompt, String chatId, File file) throws IOException {
        HttpURLConnection conn = (HttpURLConnection) new URL(urlString).openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

        try (OutputStream output = conn.getOutputStream();
             PrintWriter writer = new PrintWriter(new OutputStreamWriter(output))) {

            // 添加 text 参数: prompt
            addFormField(writer, "prompt", prompt);

            // 添加 text 参数: chatId
            addFormField(writer, "chatId", chatId);

            // 添加文件参数（如果存在）
            if (file != null && file.exists()) {
                addFilePart(writer, output, "files", file);
            }

            // 结束边界
            writer.append("--").append(BOUNDARY).append("--").append("\r\n");
            writer.flush();
        }

        // 获取响应
        int responseCode = conn.getResponseCode();
        System.out.println("Response Code: " + responseCode);

        StringBuilder response = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
        }

        return response.toString();
    }

    private static void addFormField(PrintWriter writer, String name, String value) {
        writer.append("--").append(BOUNDARY).append("\r\n");
        writer.append("Content-Disposition: form-data; name=\"").append(name).append("\"\r\n\r\n");
        writer.append(value).append("\r\n");
    }

    private static void addFilePart(PrintWriter writer, OutputStream output, String fieldName, File file) throws IOException {
        writer.append("--").append(BOUNDARY).append("\r\n");
        writer.append("Content-Disposition: form-data; name=\"")
                .append(fieldName).append("\"; filename=\"").append(file.getName()).append("\"\r\n");
        writer.append("Content-Type: application/octet-stream\r\n\r\n");
        writer.flush();
        Files.copy(file.toPath(), output);
        output.flush();
        writer.append("\r\n");
    }

    // 测试调用
    public static void main(String[] args) {
        try {
            String url = "http://172.18.1.42:8080/ai/chat";
            String prompt = "你好";
            String chatId = "151615000326195207";
            File file = null; // 如果没有文件可以设为 null

            String result = sendMultipartRequest(url, prompt, chatId, file);
            System.out.println("Server Response: " + result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
